//1.导入模块
const express = require('express')
const request = require('request')
var path = require("path");
const xmlparser = require('express-xml-bodyparser');
const bodyParser = require('body-parser');
// 微信加密签名
const crypto = require('crypto');
// svg转换json库
const xml2js = require('xml2js');
const fs = require('fs');
// 路由
const router = express.Router();
router.get('/', function (req, res, next) {
  res.render('index', {
    title: 'Express'
  });
});

//2.创建服务器
let app = express()
// 允许跨域
app.all('*', function (req, res, next) {

  res.header("Access-Control-Allow-Origin", req.headers.origin);
  // res.header("Access-Control-Allow-Origin", '*');
  res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Credentials", "true");
  res.header("X-Powered-By", ' 3.2.1')
  if (req.method === "OPTIONS") res.send(200); /*让options请求快速返回*/
  else next();
});
app.use(xmlparser());
app.use("/frontend/index.html", express.static(path.join(__dirname, "./staticPages/dist/index.html"))) //邀请页面
app.use("/frontend/redirect", express.static(path.join(__dirname, "./staticPages/redirectPages.html"))) //重定向页面
app.use("/frontend/skipminiprogram", express.static(path.join(__dirname, "./staticPages/nextSkipPages.html"))) //跳转小程序页面
// 格式化参数
app.use(express.json())
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(bodyParser.json());
app.use((req, res, next) => {
  res.setHeader('Content-Security-Policy', "font-src 'self' http://localhost:9090;");
  next();
});



app.use(express.static('testtest'));
// vue打包文件
// css
app.get('/frontend/appb41cbdee.css', function (req, res) {
  res.type('text/css');
  res.sendFile(__dirname + '/staticPages/dist/css/app.a2c530ac.css');
});
app.get('/frontend/chunk-vendors9ddc568c.css', function (req, res) {
  res.type('text/css');
  res.sendFile(__dirname + '/staticPages/dist/css/chunk-vendors.9ddc568c.css');
});
// js
app.get('/frontend/appc5a747a8.js', function (req, res) {
  res.type('text/javascript');
  res.sendFile(__dirname + '/staticPages/dist/js/app.522b44f6.js');
});
app.get('/frontend/248.bbe1179a.js', function (req, res) {
  res.type('text/javascript');
  res.sendFile(__dirname + '/staticPages/dist/js/248.bbe1179a.js');
});
app.get('/frontend/623.f491ecbe.js', function (req, res) {
  res.type('text/javascript');
  res.sendFile(__dirname + '/staticPages/dist/js/623.f491ecbe.js');
});
app.get('/frontend/chunk-vendorsbd3c7cf7.js', function (req, res) {
  res.type('text/javascript');
  res.sendFile(__dirname + '/staticPages/dist/js/chunk-vendors.5314a278.js');
});
// 小程序校验文件目录
app.get('/frontend/MP_verify_7EsaE8XInVGwUvux.txt', function (req, res) {
  res.sendFile(__dirname + '/MP_verify_7EsaE8XInVGwUvux.txt');
});
app.get('/frontend/RKDK342248.txt', function (req, res) {
  res.sendFile(__dirname + '/RKDK342248.txt');
});
app.get('/frontend/base64data.json', function (req, res) {
  res.sendFile(__dirname + '/base64.json');
});
// 获取公众号的openid
app.get('/frontend/officialAccounts', (req, res) => {
  const appid = 'wxdc7ed0f21b5d80bf'
  const appsecret = 'c7dbd345efa677d3b121040085b66fb3'
  request(
    `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${appsecret}&js_code=${req.query.code}&grant_type=authorization_code`,
    function (err, response, body) {
      res.send(body)
    }
  )
})
// 获取公众号的unionId
app.get('/frontend/officialAccountsUnionId', (req, res) => {
  const appid = 'wxdc7ed0f21b5d80bf'
  const appsecret = 'c7dbd345efa677d3b121040085b66fb3'
  let access_token = ''
  request(
    `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`,
    function (err, response, body) {
      access_token = body.access_token
      request(`https://api.weixin.qq.com/cgi-bin/user/info?access_token=${access_token}&openid=${req.query.openId}`,
        function (err, response, body) {
          res.send(body)
        })
    }
  )
})

// 建档接口
// const baseURl = 'https://mock.apifox.cn/m1/2562523-0-default/api';
const baseURl = 'http://localhost:8101/api';
// get登录接口获取openid
app.get('/frontend/secondTrialLogin', (req, res) => {
  request(
    `https://api.weixin.qq.com/sns/jscode2session?appid=wx5829252f188052a7&secret=02a1995f8c318d3c38455144c6bcaa1c&js_code=${req.query.code}&grant_type=authorization_code`,
    function (err, response, body) {
      res.send(body)
    })
})
// 邀请建档
app.post('/frontend/api/personinfo/invite', (req, res) => {
  request({
    url: baseURl + '/personInfo/invite',
    method: "POST",
    json: true,
    body: req.body
  }, (err, rep, body) => {
    if (err) {
      console.log("request 请求post 出现错误 err : ", err);
      res.send("request 请求post 出现错误 err : ", err)
      return false;
    }
    // body表示返回的数据
    if (body) {
      // 请求成功
      // res.set('Content-Type', 'application/json');
      // res.json(body);
      res.send(body)
    }
  })
})
// 通过access_token获取公众号的openid
app.get('/frontend/sofficialAccountAccessOpenid', (req, res) => {
  const appid = 'wxdc7ed0f21b5d80bf'
  const appsecret = 'c7dbd345efa677d3b121040085b66fb3'
  request(
    `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`,
    function (err, response, body) {
      let access_token = JSON.parse(body).access_token
      request(`https://api.weixin.qq.com/cgi-bin/user/get?access_token=${access_token}`, function (err, response, body) {
        res.send(body)
      })
    })
})

// 公众号获取openid
app.get('/frontend/sofficialAccount', (req, res) => {
  const appid = 'wxdc7ed0f21b5d80bf'
  const appsecret = 'c7dbd345efa677d3b121040085b66fb3'
  request(
    `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${appsecret}&js_code=${req.query.code}&grant_type=authorization_code`,
    function (err, response, body) {
      console.log(body, '---------数据')
      res.send(body)
    })
})
// 创建微信用户
app.post('/frontend/api/userInfo/wechat', (req, res) => {
  request({
    url: baseURl + '/userInfo/wechat',
    method: "POST",
    json: true,
    body: req.body
  }, (err, rep, body) => {
    if (err) {
      console.log("request 请求post 出现错误 err : ", err);
      res.send("request 请求post 出现错误 err : ", err)
      return false;
    }
    // body表示返回的数据
    if (body) {
      // 请求成功
      res.send(body)
    }
  })
})
// 获取用户微信信息
app.get('/frontend/api/userInfo/wechat', (req, res) => {
  request(
    baseURl + `/userInfo/wechat?familyMemberId=${req.query.familyMemberId}`,
    function (err, response, body) {
      res.setHeader('Content-Type', 'application/json');
      res.send(body)
    })
})

// 获取当前用户信息
app.get('/frontend/api/userInfo', (req, res) => {
  request(
    baseURl + `/userInfo?userId=${req.query.userId}&wechatServiceOfficialAccountOpenId=${req.query.wechatServiceOfficialAccountOpenId}&wechatUnionId=${req.query.wechatUnionId}&wechatMiniprogramOpenId=${req.query.wechatMiniprogramOpenId}`,
    function (err, response, body) {
      res.setHeader('Content-Type', 'application/json');
      res.send(body)
    })
})

// 根据版本号获取用户协议
app.get('/frontend/api/agreement', (req, res) => {
  request(
    baseURl + `/agreement?version=${req.query.version}`,
    function (err, response, body) {
      res.setHeader('Content-Type', 'application/json');

      res.send(body)
    })
})
// 签署协议
app.post('/frontend/api/agreement/sign', (req, res) => {
  request({
    url: baseURl + '/agreement/sign',
    method: "POST",
    json: true,
    body: req.body
  }, (err, rep, body) => {
    if (err) {
      console.log("request 请求post 出现错误 err : ", err);
      res.send("request 请求post 出现错误 err : ", err)
      return false;
    }
    // body表示返回的数据
    if (body) {
      // 请求成功
      res.send(body)
    }
  })
})
// 更新建档状态接口
app.patch('/frontend/api/familyArchiveStatus', (req, res) => {
  request({
    url: baseURl + '/familyArchiveStatus',
    method: "PATCH",
    json: true,
    body: req.body
  }, (err, rep, body) => {
    if (err) {
      console.log("request 请求post 出现错误 err : ", err);
      return false;
    }
    // body表示返回的数据
    if (body) {
      // 请求成功
      res.send(body)
    }
  })
})
// 获取用户个人信息
app.get('/frontend/api/personInfo', (req, res) => {
  request(
    baseURl + `/personInfo?userId=${req.query.userId}&persionId=${req.query.persionId}`,
    function (err, response, body) {
      res.setHeader('Content-Type', 'application/json');

      res.send(body)
    })
})
// 修改个人信息
app.patch('/frontend/api/personInfo', (req, res) => {
  request({
    url: baseURl + '/personInfo',
    method: "PATCH",
    json: true,
    body: req.body
  }, (err, rep, body) => {
    if (err) {
      console.log("request 请求post 出现错误 err : ", err);
      return false;
    }
    // body表示返回的数据
    if (body) {
      // 请求成功
      res.send(body)
    }
  })
})

//自主建档填写个人信息
app.post('/frontend/api/personInfo/self', (req, res) => {
  request({
    url: baseURl + '/personInfo/self',
    method: "POST",
    json: true,
    body: req.body
  }, (err, rep, body) => {
    if (err) {
      console.log("request 请求post 出现错误 err : ", err);
      res.send("request 请求post 出现错误 err : ", err)
      return
    }
    // body表示返回的数据
    if (body) {
      // 请求成功
      res.send(body)
    }
  })
})
// 获取字典信息
app.get('/frontend/api/dataDictionary/familyMemberRelationship', (req, res) => {
  request(
    baseURl + `/dataDictionary/familyMemberRelationship`,
    function (err, response, body) {
      res.setHeader('Content-Type', 'application/json');
      res.send(body)
    })
})
//添加家庭成员信息
app.post('/frontend/api/familyMember', (req, res) => {
  request({
    url: baseURl + '/familyMember',
    method: "POST",
    json: true,
    body: req.body
  }, (err, rep, body) => {
    if (err) {
      console.log("request 请求post 出现错误 err : ", err);
      return false;
    }
    // body表示返回的数据
    if (body) {
      // 请求成功
      res.send(body)
    }
  })
})
// 获取家庭成员信息
app.get('/frontend/api/familyMember', (req, res) => {
  request(
    baseURl + `/familyMember?familyId=${req.query.familyId}&hasPerson=${req.query.hasPerson}&familyMemberId=${req.query.familyMemberId}`,
    function (err, response, body) {
      console.log(body);
      res.setHeader('Content-Type', 'application/json');

      res.send(body)
    })
})
//修改家庭成员信息
app.patch('/frontend/api/familyMember', (req, res) => {
  request({
    url: baseURl + '/familyMember',
    method: "PATCH",
    json: true,
    body: req.body
  }, (err, rep, body) => {
    if (err) {
      console.log("request 请求post 出现错误 err : ", err);
      return false;
    }
    // body表示返回的数据
    if (body) {
      // 请求成功
      res.send(body)
    }
  })
})
// 删除家庭成员信息
app.delete('/frontend/api/familyMember', (req, res) => {
  console.log(req.query.familyMemberId);
  request({
    url: baseURl + `/familyMember?familyMemberId=${req.query.familyMemberId}`,
    method: 'delete',
  }, function (err, response, body) {
    res.send(body)
  })
})
// 绑定家庭成员信息
app.patch('/frontend/api/healthManage/bind', (req, res) => {
  request({
    url: baseURl + '/healthManage/bind',
    method: "PATCH",
    json: true,
    body: req.body
  }, (err, rep, body) => {
    if (err) {
      console.log("request 请求post 出现错误 err : ", err);
      return false;
    }
    // body表示返回的数据
    if (body) {
      // 请求成功
      res.send(body)
    }
  })
})
// 添加健康管理
app.post('/frontend/api/healthManage', (req, res) => {
  request({
    url: baseURl + '/healthManage',
    method: "POST",
    json: true,
    body: req.body
  }, (err, rep, body) => {
    if (err) {
      console.log("request 请求post 出现错误 err : ", err);
      return false;
    }
    // body表示返回的数据
    if (body) {
      // 请求成功
      res.send(body)
    }
  })
})
// 确认健康管理申请
app.post('/frontend/api/healthManageRequest/confirm', (req, res) => {
  console.log(123)
  request({
    url: baseURl + '/healthManage/confirm',
    method: "POST",
    json: true,
    body: req.body
  }, (err, rep, body) => {
    if (err) {
      console.log("request 请求post 出现错误 err : ", err);
      return false;
    }
    // body表示返回的数据
    if (body) {
      // 请求成功
      res.send(body)
    }
  })
})
// 删除健康管理关系
app.delete('/frontend/api/healthManage', (req, res) => {
  console.log(req.body)
  request({
    url: baseURl + `/healthManage?id=${Number(req.query.id) }`,
    method: 'delete',
  }, function (err, response, body) {
    res.send(body)
  })
})
// 获取健康管理关系
app.get('/frontend/api/healthManage', (req, res) => {
  request(
    baseURl + `/healthManage?familyId=${req.query.familyId}`,
    function (err, response, body) {
      res.setHeader('Content-Type', 'application/json');
      res.send(body)
    }
  )
})
// 更新健康管理关系
app.put('/frontend/api/healthManage', (req, res) => {
  request({
    url: baseURl + '/healthManage',
    method: "PUT",
    json: true,
    body: req.body
  }, (err, rep, body) => {
    if (err) {
      console.log("request 请求post 出现错误 err : ", err);
      return false;
    }
    // body表示返回的数据
    if (body) {
      // 请求成功
      res.send(body)
    }
  })
})
// 获取健康管理申请详情
app.get('/frontend/api/healthManage/healthManageConfirmRequest', (req, res) => {
  request(
    baseURl + `/healthManage/healthManageConfirmRequest?id=${req.query.id}`,
    function (err, response, body) {
      res.setHeader('Content-Type', 'application/json');
      res.send(body)
    }
  )
})

// 健康管理申请
app.use("/frontend/healthManagement", express.static(path.join(__dirname, "./staticPages/healthManagementView.html")))
app.use("/frontend/test", express.static(path.join(__dirname, "./staticPages/test.html")))


// 公众号推送消息
app.get('/frontend/api/OfficialAccounts', (req, res) => {
  const appid = 'wxdc7ed0f21b5d80bf'
  const appsecret = 'c7dbd345efa677d3b121040085b66fb3'
  let serviceOfficialAccountOpenid = ''
  let requestId = req.query.requestId
  let familyMemberId = req.query.familyMemberId
  request(baseURl + `/userInfo/wechat?familyMemberId=${familyMemberId}`, function (err, response, body) {
    serviceOfficialAccountOpenid = JSON.parse(body).data.serviceOfficialAccountOpenid
    console.log(JSON.parse(body), '----------------JSON.parse(body)')
    request(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`,
      function (err, response, body) {
        let access_token = JSON.parse(body).access_token
        console.log(JSON.parse(body), '------access_token');
        let params = {
          "touser": serviceOfficialAccountOpenid,
          "template_id": "6c55gHsAVSNHeKEawv3BZd_mgY0NJTCE4LYlmcNMzjY",
          "url": `https://zg.particlesoft.info/frontend/healthManagement?requestId=${requestId}&familyMemberId=${familyMemberId}`,
          // "miniprogram": {
          //   "appid": appid,
          //   "pagepath": "https://zg.particlesoft.info/frontend/inviteView"
          // },
          "data": {
            "first": {
              "value": "我是first！",
              "color": "#173177"
            },
            "keyword1": {
              "value": "keyword1",
              "color": "#173177"
            },
            "keyword2": {
              "value": "keyword2",
              "color": "#173177"
            },
            "keyword3": {
              "value": "keyword3",
              "color": "#173177"
            },
            "remark": {
              "value": "备注",
              "color": "#173177"
            }
          },
        }
        request({
          url: `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${access_token}`,
          method: "POST",
          json: true,
          body: params
        }, (err, rep, body) => {
          if (err) {
            console.log("request 请求post 出现错误 err : ", err);
            return false;
          }
          // body表示返回的数据
          if (body) {
            // 请求成功
            res.send(body)
          }
        })
      })
  })
})

// 验证消息是否来自微信
function checkSignature(signature, timestamp, nonce) {
  const token = 'particlesoft'; // 这里填写在公众平台设置的令牌
  const tmpArr = [token, timestamp, nonce].sort();
  const tmpStr = tmpArr.join('');
  // 使用sha1加密算法
  const sha1 = crypto.createHash('sha1');
  sha1.update(tmpStr);
  const encryptStr = sha1.digest('hex');
  if (encryptStr === signature) {
    return true;
  } else {
    return false
  }
}


// 微信监听用户是否关注公众号接口
app.post('/frontend/', (req, res) => {
  console.log(req.headers['content-type']);
  const signature = req.query.signature;
  const timestamp = req.query.timestamp;
  const nonce = req.query.nonce;
  if (checkSignature(signature, timestamp, nonce)) {
    console.log(signature, timestamp, nonce, '====== 签名');
    const txMessage = req.query;
    const openId = txMessage.openid
    const appid = 'wxdc7ed0f21b5d80bf'
    const appsecret = 'c7dbd345efa677d3b121040085b66fb3'
    request(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`, function (err, response, body) {
      let access_token = JSON.parse(body).access_token
      request(`https://api.weixin.qq.com/cgi-bin/user/info?access_token=${access_token}&openid=${openId}&lang=zh_CN`, function (err, response, body) {
        let offunionId = JSON.parse(body).unionid
        console.log(offunionId, "offunionId=================");
        console.log(JSON.parse(body), "aaaaaaaaaaaaaaaaaa=================");
        if (JSON.parse(body).subscribe == 1) {
          request({
            url: baseURl + '/userInfo/wechat',
            method: "POST",
            json: true,
            body: {
              serviceOfficialAccountOpenid: openId,
              miniprogramOpenid: '',
              unionid: offunionId
            }
          }, (err, rep, body) => {
            if (err) {
              console.log("request 请求post 出现错误 err : ", err);
              res.send("request 请求post 出现错误 err : ", err)
              return false;
            }
            // body表示返回的数据
            if (body) {
              // 请求成功
              console.log(body)
              res.send('success');
            }
          })
        } else {
          res.send('success');
        }

      })
    })
    console.log(txMessage, '======xml');
  } else {
    res.send('err');
  }
});
// 微信监听用户是否关注公众号接口
app.get('/frontend/', (req, res) => {
  // const contentType = req.headers['content-type'];
  const signature = req.query.signature;
  const timestamp = req.query.timestamp;
  const nonce = req.query.nonce;
  const echostr = req.query.echostr;
  if (checkSignature(signature, timestamp, nonce)) {
    // 验证通过，可以处理接收到的消息
    console.log(signature, timestamp, nonce, '====== 签名');
    res.send(echostr);
  } else {
    // 验证失败，不处理消息
    res.send('err');
  }
});
// 人体模型svg图片请求

app.get('/frontend/asset/geo', (req, res) => {
  request('https://echarts.apache.org/examples/data/asset/geo/Veins_Medical_Diagram_clip_art.svg', function (err, response, body) {
    res.send(body)
    // xml2js.parseString(body, (error, result) => {
    //   if (error) {
    //     console.error('解析 SVG 文件失败：', error);
    //     res.send(error);
    //   } else {
    //     // 遍历 DOM 对象，并将每个元素转换为 JSON 对象
    //     const json = traverse(result);
    //     res.send(json);
    //   }
    // });
  })
});
// 多家庭

//修改家庭成员信息
app.put('/frontend/api/family/updateDefaultFamily', (req, res) => {
  request({
    url: baseURl + '/family/updateDefaultFamily',
    method: "PUT",
    json: true,
    body: req.body
  }, (err, rep, body) => {
    if (err) {
      console.log("request 请求post 出现错误 err : ", err);
      return false;
    }
    // body表示返回的数据
    if (body) {
      // 请求成功
      res.send(body)
    }
  })
})
// 创建家庭
app.post('/frontend/api/family/createFamily', (req, res) => {
  request({
    url: baseURl + '/family/createFamily',
    method: "POST",
    json: true,
    body: req.body
  }, (err, rep, body) => {
    if (err) {
      console.log("request 请求post 出现错误 err : ", err);
      return false;
    }
    // body表示返回的数据
    if (body) {
      // 请求成功
      res.send(body)
    }
  })
})
// 修改家庭名称
app.patch('/frontend/api/family/updateFamilyName', (req, res) => {
  request({
    url: baseURl + '/family/updateFamilyName',
    method: "PATCH",
    json: true,
    body: req.body
  }, (err, rep, body) => {
    if (err) {
      console.log("request 请求post 出现错误 err : ", err);
      return false;
    }
    // body表示返回的数据
    if (body) {
      // 请求成功
      res.send(body)
    }
  })
})
// 查询家庭名称
app.get('/frontend/api/family', (req, res) => {
  request(
    baseURl + `/family?familyId=${req.query.familyId}`,
    function (err, response, body) {
      res.setHeader('Content-Type', 'application/json');
      res.send(body)
    })
})
//3.开启服务器
app.listen(9090, () => {
  console.log('服务器开启');
})